package chagine.core.restful.util;

import chagine.core.Env;
import chagine.core.ErrorCode;
import chagine.core.current.CurrentRequestID;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * 用于基本信息的序列化与反序列化
 * Created by wba on 2016/12/30.
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@Setter
public class HResponse<DataType> {

    @JsonProperty("request_id")
    private String requestId;
    private String status;
    private String message;
    private DataType data;

    public HResponse() {
        requestId = String.valueOf(CurrentRequestID.currentRequestID());
        readRequestIdFromHeader();
    }

    @SuppressWarnings("unchecked")
    public HResponse(String status, DataType data, String message) {
        this();
        this.status = status;
        this.message = message;
        this.data = data;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return ErrorCode.Success.equals(status);
    }

    private void readRequestIdFromHeader() {
        if ("null".equals(requestId)) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                return;
            }
            HttpServletResponse response = requestAttributes.getResponse();
            if (response == null) {
                return;
            }
            this.requestId = response.getHeader(Env.HEAD_REQUEST_ID_KEY);
        }
    }
}
